package com.company.Thread.JUC;

import cn.hutool.core.date.DateTime;
import com.company.Main;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockMain {

    static ConcurrentHashMap<Integer, ReentrantLock> hashMap;

    public static void main(String[] args) {
        hashMap = new ConcurrentHashMap<>();
        Main.threadTest(16, item -> {
            ReentrantLock lock = hashMap.putIfAbsent(item % 8, new ReentrantLock());
            if (lock == null) {
                lock = hashMap.get(item % 8);
            }
            Integer lockNum = lock.hashCode();
            System.out.println("，时间：" + DateTime.now());
            if (item % 4 == 3) {
                if (!lock.tryLock()) {
                    System.out.println(lockNum + "获取锁失败");
                } else {
                    try {
                        lock.lock();
                        System.out.println(lockNum + "锁住3秒" + "，时间：" + DateTime.now());
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        System.out.println(lock.hasQueuedThreads());
                        if (!lock.hasQueuedThreads()) {// 后面有人在排队了，删除这个锁
                            hashMap.remove(item % 4);
                        }
                        lock.unlock();
                        System.out.println(lockNum + "释放锁" + "，时间：" + DateTime.now());
                    }
                }
            } else {
                try {
                    lock.lock();
                    System.out.println(lockNum + "锁住1秒" + "，时间：" + DateTime.now());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                    System.out.println(lockNum + "释放锁" + "，时间：" + DateTime.now());
                }
            }
        });
    }
}
